import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router';

const service = axios.create({
  baseURL: 'http://localhost:8088/',
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest'
  }
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    const url = config.url;
    if (url.startsWith('/sys')) {
      const token = localStorage.getItem('access-token')
      if (!token) {
        localStorage.removeItem('access-token');
        router.push('/login');
        return Promise.reject(new Error('请先登录'));
      }
      config.headers['Authorization'] = token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return response.data;
    } else {
      ElMessage({message: response.data.message, type: 'error', duration: 3 * 1000, showClose: true});
    }
  },
  error => {
    ElMessage({message: error.message, type: 'error', duration: 3 * 1000, showClose: true});
    return Promise.reject(error);
  }
);

export default service;
